//package xyz.second.training_manage_system.filter;
//
//import org.springframework.http.HttpStatus;
//import xyz.second.common.auth.UserSessionData;
//import xyz.second.common.auth.UserType;
//
//import javax.servlet.*;
//import javax.servlet.annotation.WebFilter;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import javax.servlet.http.HttpSession;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Session过滤器，对特定路由的访问进行拦截
// * 部分路由必须要经过权限认证才可放行
// * @author wjw
// */
//@WebFilter(filterName = "SessionFilter", urlPatterns = "/*")
//public class SessionFilter implements Filter {
//
//    private final List<UserType> userTypes = new ArrayList<>();
//
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
//        userTypes.add(UserType.USER_TYPE_ADMIN);
//        userTypes.add(UserType.USER_TYPE_TEACHER);
//        userTypes.add(UserType.USER_TYPE_STUDENT);
//    }
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        HttpSession session = request.getSession(false);
//        String uri = request.getRequestURI();
//
//        // 从路由中匹配访问该路由需要的用户类型权限
//        // 访问的原则是，当路由中包含admin、student、teacher时，则需要对应的session认证
//        UserType pathUserType = matchUserType(uri);
//
//        // 该路由不包含需要认证
//        if (pathUserType == null) {
//            filterChain.doFilter(servletRequest, servletResponse);
//            return;
//        }
//
//        if (session != null) {
//            Object sessionDataObj = session.getAttribute(UserSessionData.SESSION_DATA_KEY);
//            // 该路由已认证，系统中包含该session，且该角色可以访问该路由
//            if (sessionDataObj != null && ((UserSessionData) sessionDataObj).getUserType().equals(pathUserType.getName())) {
//                filterChain.doFilter(servletRequest, servletResponse);
//                return;
//            }
//            response.sendError(HttpStatus.FORBIDDEN.value());
//        }
//
//        response.sendError(HttpStatus.UNAUTHORIZED.value());
//    }
//
//    @Override
//    public void destroy() {
//        Filter.super.destroy();
//    }
//
//    private UserType matchUserType(String uri) {
//        return userTypes.stream().filter(userType -> uri.contains(userType.getName()))
//                .findFirst().orElse(null);
//    }
//}
